package com.queen.testretrofitrxjava.http;

import android.util.Log;


import com.queen.testretrofitrxjava.entity.HttpResult;
import com.queen.testretrofitrxjava.entity.Subject;
import com.queen.testretrofitrxjava.internal.di.modules.ApiClientModule;

import java.util.List;
import java.util.concurrent.TimeUnit;


import javax.inject.Inject;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liukun on 16/3/5.
 */
public class HttpMethods {

    public static final String TAG = HttpMethods.class.getSimpleName();

//    public static final String BASE_URL = "https://api.douban.com/v2/movie/";

//    private Retrofit retrofit;

//    private MovieService movieService;

//    @Inject
    private MovieService movieService;

//    @Inject
    public HttpMethods(MovieService movieService) {

//        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        builder.connectTimeout(5, TimeUnit.SECONDS);
//
//        retrofit = new Retrofit.Builder()
//                .client(builder.build())
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//                .baseUrl(BASE_URL)
//                .build();
//
//        movieService = retrofit.create(MovieService.class);

//        DaggerApiClientComponent.builder().apiClientModule(new ApiClientModule()).build().inject(this);

        this.movieService = movieService;
    }

//    private static class SingletonHolder{
//        private static final HttpMethods INSTANCE = new HttpMethods();
//    }
//
//    public static HttpMethods getInstance(){
//        return SingletonHolder.INSTANCE;
//    }

    public void getTopMovie(Subscriber<List<Subject>> subscriber, int start, int count){

//        movieService = retrofit.create(MovieService.class);

//        movieService.getTopMovie(start, count)
//                .flatMap(new Func1<HttpResult<List<Subject>>, Observable<List<Subject>>>() {
//                    @Override
//                    public Observable<List<Subject>> call(HttpResult<List<Subject>> listHttpResult) {
//                        return flatResult(listHttpResult);
//                    }
//                })
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(subscriber);


        movieService.getTopMovie(start, count)
                .compose(new HttpObservableTransformer<List<Subject>>())
                .subscribe(subscriber);

    }


    public void getTopMovieHttpResult(Subscriber<HttpResult> subscriber, int start, int count){

//        movieService = retrofit.create(MovieService.class);

        movieService.getTopMovie(start, count)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public void getMovieDetail(Subscriber<Subject> subscriber, String movieId){
        movieService.getMovieDetail(movieId)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    /**
     * 用来统一处理Http的ResultCode
     * @param <T> Subscriber真正需要的数据类型，也就是Data部分的数据类型
     */
    private class HttpObservableTransformer<T> implements Observable.Transformer<HttpResult<T>, T> {

        @Override
        public Observable<T> call(Observable<HttpResult<T>> httpObservable) {

            return httpObservable.map(new Func1<HttpResult<T>, T>() {
                @Override
                public T call(HttpResult<T> httpResult) {
                    if (httpResult.getCount() == 0) {
                        throw new ApiException(100);
                    }
                    return httpResult.getSubjects();
                }
            })
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }
    }
//
//    /**
//     * 用来统一处理Http的ResultCode
//     * @param result   Http请求返回的数据，用过HttpResult进行了封装
//     * @param <T>   Subscriber真正需要的数据类型，也就是Data部分的数据类型
//     * @return
//     */
//    static <T> Observable<T> flatResult(final HttpResult<T> result) {
//        return Observable.create(new Observable.OnSubscribe<T>() {
//            @Override
//            public void call(Subscriber<? super T> subscriber) {
//
//                if (result.getCount() == 0) {
//                    if (!subscriber.isUnsubscribed()) {
//                        subscriber.onError(new ApiException(100));
//                    }
//
//                } else{
//                    if (!subscriber.isUnsubscribed()) {
//                        subscriber.onNext(result.getSubjects());
//                    }
//                }
//                if (!subscriber.isUnsubscribed()) {
//                    subscriber.onCompleted();
//                }
//            }
//        });
//    }


}
